package com.application.lucky.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.application.lucky.Lucky;
import com.application.lucky.R;
import com.application.lucky.bean.UserBean;
import com.application.lucky.bean.eventbean.UpdateUserInfo;
import com.application.lucky.config.Config;
import com.application.lucky.gen.UserBeanDao;
import com.application.lucky.manager.UserManagers;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.UserRequest;
import com.application.lucky.request.nav.UrlManager;
import com.application.lucky.utils.FileUtil;
import com.application.lucky.utils.Flog;
import com.application.lucky.utils.TopActivityManager;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.bottombar.UIUtils;
import com.application.lucky.widget.dialog.TwoButtonDialog;
import com.application.mylibrary.base.BaseActivity;
import com.application.mylibrary.utils.EventBusUtils;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.bruce.pickerview.popwindow.DatePickerPopWin;
import com.bumptech.glide.Glide;
import com.lcw.library.imagepicker.ImagePicker;
import com.lcw.library.imagepicker.utils.ImageLoader;
import com.qunar.im.ui.util.ProfileUtils;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MyInfoActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MyInfoActivity";

    private static final int REQUEST_SELECT_IMAGES_CODE = 11;
    private static final int REQUEST_CHANGE_NICK = 12;
    private TitlebarView mTitleBar;

    private View layout_head;
    private ImageView iv_head_view;
    private View layout_nick;
    private TextView tv_nick;
    private View layout_user_name;
    private TextView tv_user_name;
    private View layout_birthday;
    private TextView tv_birthday;
    private View layout_zcode;
    private ImageView iv_zcode;
    private View layout_zone;
    private TextView tv_zone;
    private TextView tv_logout;

    private String id;
    private String uname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        loadData();
    }

    private void loadData() {
        if (TextUtils.isEmpty(id)) {
            new UserRequest().getSelfData(new CallBackEx<BaseResponse<UserBean>>() {
                @Override
                public void onSuccess(BaseResponse<UserBean> userBeanBaseResponse) {
                    if (userBeanBaseResponse.dataInfo != null) {
                        setUi(userBeanBaseResponse.dataInfo);
                    }
                }

                @Override
                public void onFailed(int code) {

                }
            });
        }
    }

    public void setUi(UserBean dataInfo) {
        ProfileUtils.displayGravatarByImageSrc(MyInfoActivity.this, UrlManager.getHeadPic(dataInfo.getHeadPic()), iv_head_view);
        tv_nick.setText(dataInfo.getShowName());
//        setUid(dataInfo.getUserId() + "");
        tv_user_name.setText(dataInfo.getNickName());
        tv_birthday.setText(calTime(dataInfo.getBirthday()));
        tv_zone.setText(dataInfo.getCity());
    }

    private String calTime(String birthday) {
        if (TextUtils.isEmpty(birthday)) {
            return "";
        }
        long time = Long.parseLong(birthday);
        Date date = new Date();
        date.setTime(time);
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    private void setUid(String uid) {
        try {
            Long integer = Long.valueOf(uid);
            tv_user_name.setText("" + (integer ^ Config.ID_proguard));
        } catch (Exception e) {
            tv_user_name.setText("" + uid);
        }
    }

    private void initView() {
        mTitleBar = (TitlebarView) findViewById(R.id.title_bar);
        mTitleBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                onBackPressed();
            }

            @Override
            public void rightClick() {

            }
        });

        layout_head = findViewById(R.id.layout_head);
        iv_head_view = (ImageView) findViewById(R.id.iv_head_view);
        layout_nick = findViewById(R.id.layout_nick);
        tv_nick = findViewById(R.id.tv_nick);
        layout_user_name = findViewById(R.id.layout_user_name);
        tv_user_name = findViewById(R.id.tv_user_name);
        layout_birthday = findViewById(R.id.layout_birthday);
        tv_birthday = findViewById(R.id.tv_birthday);
        layout_zcode = findViewById(R.id.layout_zcode);
        iv_zcode = findViewById(R.id.iv_zcode);
        layout_zone = findViewById(R.id.layout_zone);
        tv_zone = findViewById(R.id.tv_zone);
        tv_logout = findViewById(R.id.tv_logout);

        layout_head.setOnClickListener(this);
        layout_nick.setOnClickListener(this);
        layout_user_name.setOnClickListener(this);
        layout_birthday.setOnClickListener(this);
        layout_zcode.setOnClickListener(this);
        layout_zone.setOnClickListener(this);
        tv_logout.setOnClickListener(this);
    }

    @Override
    public void beforeInit() {
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        uname = intent.getStringExtra("uname");
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_my_info;
    }

    public static void jump(Context context, String id, String uname) {
        Intent intent = new Intent(context, MyInfoActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("uname", uname);
        context.startActivity(intent);
    }

    public static void jumpForResult(Context context, String id, String uname) {
        Intent intent = new Intent(context, MyInfoActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("uname", uname);
        if (context instanceof Activity) {
            ((Activity) context).startActivityForResult(intent, 999);
        }
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.layout_head) {
            ImagePicker.getInstance()
                    .setTitle(getString(R.string.profile_head))//设置标题
                    .showCamera(true)//设置是否显示拍照按钮
                    .showImage(true)//设置是否展示图片
                    .showVideo(false)//设置是否展示视频
                    .setSingleType(true)//设置图片视频不能同时选择
                    .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
//                    .setImagePaths(mImageList)//保存上一次选择图片的状态，如果不需要可以忽略
                    .setImageLoader(new GlideLoader())//设置自定义图片加载器
                    .start(MyInfoActivity.this, REQUEST_SELECT_IMAGES_CODE);
        } else if (viewId == R.id.layout_nick) {
            Intent nickIntent = new Intent(MyInfoActivity.this, ChangeNickActivity.class);
            nickIntent.putExtra("nick", tv_nick.getText().toString());
            startActivityForResult(nickIntent, REQUEST_CHANGE_NICK);
        } else if (viewId == R.id.layout_birthday) {
            showBirthdayDialog(tv_birthday.getText().toString());
        } else if (viewId == R.id.layout_zcode) {
            Intent nickIntent = new Intent(MyInfoActivity.this, ZCodeActivity.class);
            nickIntent.putExtra("nick", tv_nick.getText().toString());
            startActivity(nickIntent);
        } else if (viewId == R.id.layout_zone) {
            showCityPicker();
        } else if (viewId == R.id.tv_logout) {
            showLogoutDialog();
        }
    }

    private void showCityPicker() {
        CityPicker.from(MyInfoActivity.this) //activity或者fragment
                .enableAnimation(true)    //启用动画效果，默认无
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        tv_zone.setText(data.getName());
                    }

                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onLocate() {
                        //定位接口，需要APP自身实现，这里模拟一下定位
//                        new Handler().postDelayed(new Runnable() {
//                            @Override
//                            public void run() {
//                                //定位完成之后更新数据
//                                CityPicker.getInstance()
//                                        .locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
//                            }
//                        }, 3000);
                    }
                })
                .show();
    }

    private void showBirthdayDialog(String birthdayText) {
        String formatBirthdayText = "2001-6-15";
        if (!TextUtils.isEmpty(birthdayText)) {
            formatBirthdayText = birthdayText;
        }

        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(MyInfoActivity.this, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                Flog.d(TAG, "onDatePickCompleted dateDesc:" + dateDesc);
                tv_birthday.setText(dateDesc);
            }
        }).textConfirm("确定") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(16)
                .viewTextSize(25)
                .colorCancel(Color.parseColor("#999999"))
                .colorConfirm(Color.parseColor("#009900"))
                .maxYear(2001)
                .dateChose(formatBirthdayText)
                .build();
        pickerPopWin.showPopWin(MyInfoActivity.this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            final List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
            Flog.d(TAG, "onActivityResult imagePaths:" + imagePaths);
            if (imagePaths != null && !imagePaths.isEmpty()) {
                showloadDialog();

                final String filePath = imagePaths.get(0);
                // 500k以内
                if (new File(filePath).length() < 1024 * 500) {
                    new UserRequest().updateHeadPic(filePath, new CallBackEx<BaseResponse<String>>() {
                        @Override
                        public void onSuccess(BaseResponse<String> response) {
                            Flog.d(TAG, "updateHeadPic onSuccess response:" + response);
                            hideLoadDialog();
                            ProfileUtils.displayGravatarByImageSrc(MyInfoActivity.this, UrlManager.getHeadPic(response.dataInfo), iv_head_view);
                            EventBusUtils.postSticky(new UpdateUserInfo());
                        }

                        @Override
                        public void onFailed(int code) {
                            hideLoadDialog();
                        }
                    });
                    return;
                }

                Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(final ObservableEmitter<String> emitter) {
                        File outFile = FileUtil.compressImage(Lucky.getApplication(), filePath, UIUtils.dip2Px(Lucky.getApplication(), 100), UIUtils.dip2Px(Lucky.getApplication(), 100));
                        new UserRequest().updateHeadPic(outFile.getAbsolutePath(), new CallBackEx<BaseResponse<String>>() {
                            @Override
                            public void onSuccess(BaseResponse<String> baseResponse) {
                                Flog.d(TAG, "updateHeadPic onSuccess baseResponse:" + baseResponse);
                                emitter.onNext(baseResponse.dataInfo);
                            }

                            @Override
                            public void onFailed(int code) {
                                Flog.d(TAG, "updateHeadPic onFailed code:" + code);
                                emitter.onNext(null);
                            }
                        });
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String dataInfo) {
                        hideLoadDialog();

                        if(!TextUtils.isEmpty(dataInfo)){
                            ProfileUtils.displayGravatarByImageSrc(MyInfoActivity.this, UrlManager.getHeadPic(dataInfo), iv_head_view);
                            EventBusUtils.postSticky(new UpdateUserInfo());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

                // TODO 等待服务器接口
//                Glide.with(getApplicationContext()).load(Uri.fromFile(new File(imagePaths.get(0)))).into(iv_head_view);
//                hideLoadDialog();
            }
        } else if (REQUEST_CHANGE_NICK == requestCode && data != null) {
            String newNick = data.getStringExtra("new_nick");
            if (!TextUtils.isEmpty(newNick)) {
                tv_nick.setText(newNick);
            }
        }
    }

    class GlideLoader implements ImageLoader {

        @Override
        public void loadImage(ImageView imageView, String imagePath) {
            //小图加载
            Glide.with(imageView.getContext()).load(imagePath).centerCrop().into(imageView);
        }

        @Override
        public void loadPreImage(ImageView imageView, String imagePath) {
            //大图加载
            Glide.with(imageView.getContext()).load(imagePath).centerCrop().into(imageView);

        }

        @Override
        public void clearMemoryCache() {
            //清理缓存
            Glide.get(Lucky.getApplication()).clearMemory();
        }
    }

    private TwoButtonDialog logoutDialog;

    private void showLogoutDialog() {
        logoutDialog = new TwoButtonDialog.Build(MyInfoActivity.this)
                .disMiss(true)
                .setMessage("确定退出登录？")
                .setLeftButton("取消", null)
                .setRightButton("确定", new TwoButtonDialog.BaseDialogClickListener() {
                    @Override
                    public void click() {
                        logoutDialog.dismiss();

                        UserManagers.getInstance().loginOut();
                        TopActivityManager.getInstance().exit();
                        Intent login = new Intent(Lucky.getApplication(), LoginActivity.class);
                        login.putExtra("isout", true);
                        login.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    }
                }).create();
        logoutDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (logoutDialog != null && logoutDialog.isShowing()) {
            logoutDialog.dismiss();
            logoutDialog = null;
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();

        showloadDialog();
        String birthdayText = tv_birthday.getText().toString();
        new UserRequest().user_update_attr(tv_nick.getText().toString(), birthdayText, tv_zone.getText().toString(),
                new CallBackEx<BaseResponse<UserBean>>() {
                    @Override
                    public void onFailed(int code) {
                        hideLoadDialog();
                        finishAnim();
                    }

                    @Override
                    public void onSuccess(BaseResponse<UserBean> userBeanBaseResponse) {
                        UserBeanDao userBeanDao = Lucky.getApplication().getDaoSession().getUserBeanDao();
                        if (userBeanDao != null) {
                            UserBean userBean = UserManagers.getInstance().getUserBean();
                            userBean.setBirthday(userBean.getBirthday());
                            userBean.setNickName(userBean.getNickName());
                            userBean.setCity(userBean.getCity());
                            userBeanDao.insertOrReplace(userBean);
                            EventBusUtils.post(userBeanDao);
                            EventBusUtils.postSticky(new UpdateUserInfo());
                        }

                        hideLoadDialog();
                        finishAnim();
                    }
                });
    }

}
